import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

public class SIGNATURE {
    public static final String RSA_ALGORITHM = "RSA";
    public static final String SIGN_ALGORITHM = "SHA256withRSA";
    public static final BASE64Decoder Base64Decoder;
    public static final BASE64Encoder Base64Encoder;

    static {
        Base64Decoder = new BASE64Decoder();
        Base64Encoder = new BASE64Encoder();
    }

    // 获取RSA公钥和私钥
    public static Map<String, String> createKeys(int KeySize) {
        // 为RSA算法创建一个keyPaiGenerator对象
        KeyPairGenerator kpg;
        try {
            kpg = KeyPairGenerator.getInstance(RSA_ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalArgumentException("No such algorithm-->[" + RSA_ALGORITHM + "]");
        }
        // 初始化KeyPairGenerator对象, 密钥长度
        kpg.initialize(KeySize);
        // 生成密钥对
        KeyPair keyPair = kpg.generateKeyPair();
        // 获取公钥
        Key publicKey = keyPair.getPublic();
        // base64加密
        String publicKeyStr = Base64Encoder.encode(publicKey.getEncoded());
        // 获取私钥
        Key privateKey = keyPair.getPrivate();
        // base64加密
        String privateKeyStr = Base64Encoder.encode(privateKey.getEncoded());
        // map装载公钥和私钥
        Map<String, String> keyPairMap = new HashMap<String, String>();
        keyPairMap.put("publicKey", publicKeyStr);
        keyPairMap.put("privateKey", privateKeyStr);
        return keyPairMap;
    }


    // 公钥获取
    public static RSAPublicKey getPublicKey(String publicKey) throws Exception {
        // 通过 x509 编码的Key指令获得公钥对象
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64Decoder.decodeBuffer(publicKey));
        RSAPublicKey key = (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);
        return key;
    }

    // 私钥获取
    public static RSAPrivateKey getPrivateKey(String privateKey) throws Exception {
        // 通过 PKCS#8 编码的 Key指令获得私钥对象
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
        PKCS8EncodedKeySpec pkcs8Key = new PKCS8EncodedKeySpec(Base64Decoder.decodeBuffer(privateKey));
        RSAPrivateKey key = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8Key);
        return key;
    }

    // signature算法签名
    public static byte[] sign(byte[] data, String strPrivate) throws Exception {
        PrivateKey priK = getPrivateKey(strPrivate);
        // 实例化签名
        Signature sig = Signature.getInstance(SIGN_ALGORITHM);
        // 初始化signature
        sig.initSign(priK);
        // 更新
        sig.update(data);
        // 签名
        return sig.sign();
    }

    // 验证签名
    public static boolean verify(byte[] data, byte[] sign, String strPublic) throws Exception {
        PublicKey pubK = getPublicKey(strPublic);
        Signature sig = Signature.getInstance(SIGN_ALGORITHM);
        sig.initVerify(pubK);
        sig.update(data);
        return sig.verify(sign);
    }

    public static void main(String[] args) throws Exception {
        // 生成密钥
        Map<String, String> keyMap = RSA.createKeys(1024);
        String publicKey = keyMap.get("publicKey");
        String privateKey = keyMap.get("privateKey");
        System.out.println("公钥:\n\r" + publicKey);
        System.out.println("私钥:\n\r" + privateKey);

        System.out.println("\r\n");
        String str = "my sign data";

        byte[] signature = SIGNATURE.sign(str.getBytes(StandardCharsets.UTF_8), privateKey);
        System.out.println("原文: \n\r" + str);
        System.out.println("产生签名: \n\r" + Base64Encoder.encodeBuffer(signature));

        boolean status = SIGNATURE.verify(str.getBytes(StandardCharsets.UTF_8), signature, publicKey);
        System.out.println("验证情况: " + status);
    }
}
